import log from 'loglevel';
import {TimeUtils} from '../TimeUtils'

const plugins = [] // 插件是一个函数，有5个参数，返回一个message
let originalFactory = log.methodFactory;
log.methodFactory = function (methodName, logLevel, loggerName) {
  let rawMethod = originalFactory(methodName, logLevel, loggerName);

  return function (message) {
    let time = TimeUtils.parseTime(new Date(), "YYYY-MM-DD HH:mm:ss.SSS")
    for (let plugin of plugins) {
      message = plugin(time, methodName, logLevel, loggerName, message)
    }
    rawMethod("[" + time + "] " + "[" + methodName + "] " + "[" + loggerName + "] " + message);
  };
};
log.rebuild(); // Be sure to call the rebuild method in order to apply plugin.
const logUtils = {
  getLogger(name) {
    let ulog = log.getLogger(name)
    let old_trace = ulog.trace
    let old_debug = ulog.debug
    let old_log = ulog.log
    let old_info = ulog.info
    let old_warn = ulog.warn
    let old_error = ulog.error
    ulog.trace = (row = 0, message = '') => {
      old_trace("[row:" + row + "] " + message)
    }
    ulog.debug = (row = 0, message = '') => {
      old_debug("[row:" + row + "] " + message)
    }
    ulog.log = (row = 0, message = '') => {
      old_log("[row:" + row + "] " + message)
    }
    ulog.info = (row = 0, message = '') => {
      old_info("[row:" + row + "] " + message)
    }
    ulog.warn = (row = 0, message = '') => {
      old_warn("[row:" + row + "] " + message)
    }
    ulog.error = (row = 0, message = '') => {
      old_error("[row:" + row + "] " + message)
    }
    return ulog
  },
  addPlugin(plugin) {
    plugins.push(plugin)
  },
  removePlugin(plugin) {
    let findIndex = plugins.findIndex(i => i === plugin)
    if (findIndex > -1) {
      plugins.splice(findIndex, 1)
    }
  },
}

export default logUtils








